import { Empty, Spin } from 'antd';
import dynamic from 'next/dynamic';
import React, { useMemo } from 'react';
import { useSelector } from 'react-redux';
import { ChartType, onCardClick } from '../libs/chartCommon';
import { refineFilterCondition } from '../libs/filterCommon';
import useCustomQuery from '../libs/hooks/useCustomQuery';
import useFilterMeta from '../libs/hooks/useFilterMeta';
import useSaLogging from '../libs/hooks/useSaLogging';
import { selectFilter } from '../libs/slices/filterSlice';

const ChartSelection = dynamic(() => import('../components/ChartSelection'));
const CardTemplate = dynamic(() => import('../components/templates/CardTemplate'));

export type DetailCardWrapperNoSubFilterProps = {
  title: string;
  chartType: ChartType;
  url: string;
  dimensions: string[];
  xlabel?: string;
  metrics: string[];
  doTableSearch?: boolean;
};

function DetailCardWrapperNoSubFilter({
  title,
  chartType,
  url,
  dimensions,
  xlabel,
  metrics,
  doTableSearch = true,
}: DetailCardWrapperNoSubFilterProps) {
  const { catalog } = useFilterMeta();
  const selectedFilter = useSelector(selectFilter);
  const { saEvent } = useSaLogging();

  const condition = useMemo(() => {
    return refineFilterCondition(selectedFilter, catalog);
  }, [selectedFilter]);

  const dataFilter = useMemo(
    () => ({
      metrics,
      ...condition,
      dimensions,
    }),
    [metrics, condition, dimensions],
  );
  const { data, isLoading } = useCustomQuery({
    queryName: title,
    url,
    filter: dataFilter,
  });

  const chartComponent = useMemo(() => {
    if (!isLoading && !data) return <Empty />;
    if (!isLoading && data) {
      return (
        <ChartSelection
          data={data}
          xlabel={xlabel}
          height="200px"
          chartType={chartType}
          metrics={metrics}
          doTableSearch={doTableSearch}
        />
      );
    }
    return <Spin />;
  }, [data, isLoading, chartType]);
  return (
    <CardTemplate
      isdashboard={false}
      title={title}
      content={chartComponent}
      onClick={event => onCardClick(event, data, saEvent, catalog)}
      showSubfilter={false}
      loading={isLoading}
    />
  );
}

export default DetailCardWrapperNoSubFilter;
